#pragma once


#include <iostream>
#include <vector>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>

struct TcpSocket
{
    struct Desc
    {
        const char *host = "127.0.0.1";
        unsigned int port = 1234;

        unsigned int af = AF_INET;
        unsigned int type = SOCK_STREAM;
        unsigned int protocol = IPPROTO_TCP;

        unsigned int sinFamily = AF_INET;
    };

    int client_sock;

    bool Create(const Desc &desc)
    {
        struct sockaddr_in serv_addr;
        memset(&serv_addr, 0, sizeof(serv_addr));         // use 0 to initialize every byte
        serv_addr.sin_family = desc.sinFamily;            // use IPV4
        serv_addr.sin_addr.s_addr = inet_addr(desc.host); // define IP
        serv_addr.sin_port = htons(desc.port);            // define port

        // creat socket and establish connection with server
        client_sock = socket(desc.af, desc.type, desc.protocol);
        int res = connect(client_sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));

        if (res != 0)
        {
            printf("connect failed %d\n", res);
            return false;
        }
        printf("connect success");
        return true;
    };

    void Close()
    {
        close(client_sock); // 关闭
    }

    template <typename T>
    int Recv(T &t)
    {
        return recv(client_sock, (char *)&t, sizeof(T), 0);
    }
    template <typename T>
    int Send(const T &t)
    {
        return send(client_sock, (const char *)&t, sizeof(T), 0);
    }
};